package com.atzly.community.datasource;

import com.atzly.community.datasource.config.MyProps;
import com.baomidou.dynamic.datasource.creator.DataSourceCreator;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import javax.sql.DataSource;
import java.util.Collection;
import java.util.List;

@Slf4j
@Data
@Configuration
@ConfigurationProperties(prefix = "mysql.router")
@EnableConfigurationProperties(MyProps.class)
public class MyRouterConfig implements ApplicationRunner {

    @Autowired
    private ZookeeperService zookeeperService;

    private static final String REGISTER_PATH = "/community/apps";

    @Value("${enable:true}")
    private Boolean enable;

    @Value("${db-source:''}")
    private String dbSource;

    @Override
    public void run(ApplicationArguments args) throws Exception {
//        registerApp();
    }

    @PreDestroy
    public void destroy() {
        log.warn("正在关闭【curatorFramework】");
        log.warn("正在关闭监听器...");
        Collection<TreeCache> values = ZookeeperListenerHolder.ZK_LISTENER_CACHES.values();
        values.parallelStream().forEach(item -> {
            item.close();
        });
        log.warn("监听器关闭完成");
        zookeeperService.shutDownClient();
        log.warn("【curatorFramework】关闭成功");
    }

//    public void registerApp() {
//        MyConfig hjyConfig = ((MyConfig) SpringContextUtil.getBean("hjyConfig"));
//        String appName = hjyConfig.getAppName();
//        Integer port = hjyConfig.getPort();
//        InetAddress localHost = null;
//        try {
//            localHost = Inet4Address.getLocalHost();
//        } catch (UnknownHostException e) {
//        }
//        String ip = localHost.getHostAddress();  // 返回格式为：xxx.xxx.xxx
//        AppBean appBean = new AppBean();
//        appBean.setAppName(appName);
//        appBean.setIp(ip);
//        appBean.setPort(port);
//        appBean.setStartTime(new Date());
//        zookeeperService.createEphemeralPath(REGISTER_PATH + "/" + appName + "/" + ip + ":" + port, JSONObject.toJSONString(appBean));
//    }

    /**
     * 注册及初始化动态路由相关组件
     * @param dataSourceCreators
     * @return
     */
    @Bean
    @ConditionalOnBean(name = {"MyConfig","zookeeperService"})
    public DataSource dataSource(List<DataSourceCreator> dataSourceCreators, ZookeeperService zookeeperService, MyConfig hjyConfig ) {
        DynamicDataSource dynamicDataSource = new DynamicDataSource();
        ZookeeperPropertiesLoader.setZookeeperService(zookeeperService);
        ZookeeperPropertiesLoader.setAppId(hjyConfig.getAppId());
        DataSourceConfigManager.loadZkProperties();
        log.info("register dynamic-datasource: '{}'", dynamicDataSource);
        return dynamicDataSource;
    }

//    /**
//     * 注册及初始化动态路由相关组件
//     * @param dataSourceCreators
//     * @return
//     */
//    @Primary
//    @Bean
//    @ConditionalOnMissingBean
//    @ConditionalOnBean(name = {"dataSource"})
//    public DefaultDataSourceCreator dataSourceCreator(List<DataSourceCreator> dataSourceCreators ) {
//        HjyDataSourceCreator defaultDataSourceCreator = new HjyDataSourceCreator();
//        log.info("register DataSourceCreator: {}", defaultDataSourceCreator);
//        defaultDataSourceCreator.setCreators(dataSourceCreators);
//        return defaultDataSourceCreator;
//    }

}
